import { Pipe, PipeTransform } from "@angular/core";
import { Dictionary, DictionaryItem } from "../type/dictionary";
import { Observable } from "rxjs";
import { filterList } from "../util/filter";
import { map } from "rxjs/operators";
import { Fun1 } from "../type/fun";

@Pipe({ name: "dict" })
export class DictPipe implements PipeTransform {
  transform(
    key: string | number,
    dictionary$: Dictionary | Observable<Dictionary>
  ): string | number | Observable<string | number> {
    const filterFun: Fun1<boolean> = (item: DictionaryItem): boolean =>
      item.key === key;

    const findItem: Fun1<string | number> = (
      dictionary: Dictionary
    ): string | number => {
      const result = filterList(dictionary, filterFun);
      return result.length > 0 ? result[0].value : "";
    };

    if (dictionary$ instanceof Observable) {
      return dictionary$.pipe(map(dictionary => findItem(dictionary)));
    }

    return findItem(dictionary$);
  }
}
